#!/usr/bin/perl -w

# Copyright 2008 Jordi Carrillo 
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# This perl script is used to backup and import an existing profile
# to an existing installation of Thunderbird. Once imported, you must
# execute thunderbird -P to open the profile manager and select the newly
# created profile

use strict;
use Getopt::Std;

my %opts = ();
my $home = $ENV{'HOME'};
my $defaultPath = $home."/.mozilla-thunderbird";

getopts('t:p:',\%opts);

my $thunderbirdPath = $opts{'t'} || $defaultPath;
my $profilePath = $opts{'p'};

# Get rid of the trailing /

$thunderbirdPath =~ s/\/$//;

# Copy the profilePath to the default thunderbird path 
# to be available in the next execution

print "Copying profile to the thunderbird folder...\n";
`cp -a $profilePath $thunderbirdPath`;
print "Finished the copy to $thunderbirdPath\n";

# Get Profiles name

my @splitpath = split (/\//,$profilePath);
my $profileName = $splitpath[@splitpath-1];

my $newprofileName = undef;
my $res = undef;
do {
    print "profile Name is $profileName, do you want to change it?(y/n)\n";
    chomp ($res=<STDIN>);
}while ($res !~ /y|n/);

if ($res eq 'y') {
    print "provide another name:\n";
    chomp ($newprofileName = <STDIN>);
}

# Edit profiles.ini file to include the new profile

open IN,"<$thunderbirdPath/profiles.ini" or die "could not open profiles.ini $!\n";
chomp (my @lines = <IN>);
close IN;

my @tags = ();
# Get the last ProfileN tag with N 0....n-1
foreach (@lines) {
    if (/\[Profile(\d)\]/) {
       push @tags,$1;
   }
}
my $lastTag = pop @tags;
my $newTag = "Profile".++$lastTag;

# write the new Profile in profiles.ini

open OUT, ">>$thunderbirdPath/profiles.ini" or die "could not open for writing profiles.ini $!\n";

# Information
#[Profile2]
#Name=spinvox
#IsRelative=1
#Path=spinvoxprofile

my $Name = $newprofileName || $profileName;
print "Updating profiles.ini...\n";

print OUT "\n";
print OUT "[$newTag]\n";
print OUT "Name=$Name\n";
print OUT "IsRelative=1\n";
print OUT "Path=$profileName\n";
close OUT;
print "Finished, execute thunderbird -P to see the new profile\n";


